import React, { useContext, createContext, useReducer } from 'react';

// 核心 返回新的状态state
function reducerInAction(state, action) {
  if (typeof action.reducer == 'function') {
    return action.reducer(state);
  }
  return state;
}

// reducer in action (state, action) = > (params)
export default function createStore(params) {
  const { reducer, initialState } = {
    reducer: reducerInAction,
    initialState: {},
    ...params,
  };

  const AppContext = createContext();

  const middlewareReducer = (lastState, action) => {
    // switch (action.type) {
    //   case 'init':
    //     return { ...lastState, age: ++lastState.age };
    //   case 'increase':
    //     return { ...lastState, age: ++lastState.age };
    //   case 'decrement':
    //     return { ...lastState, age: --lastState.age };
    //   default:
    //     return { ...lastState };
    // }

    const nextState = reducer(lastState, action);
    store._state = nextState;
    return nextState;
  };

  const store = {
    _state: initialState,
    dispatch: undefined,
    getState: () => store._state,
    useContext: () => useContext(AppContext),
  };

  // Provider 灌值
  const Provider = (props) => {
    const [state, dispatch] = useReducer(middlewareReducer, initialState);

    if (!store.dispatch) {
      store.dispatch = async (action) => {
        if (typeof action === 'function') {
          // 异步处理
          await action(dispatch, store.getState());
        } else {
          dispatch(action);
        }
      };
    }

    return <AppContext.Provider {...props} value={state} />;
  };

  return {
    Provider,
    store,
  };
}
